import { defineStore } from 'pinia';
import * as echarts from 'echarts';

export const useEchartsStore = defineStore('echarts', {
  state: () => ({
    chartInstance: null,
    isChartInitialized: false,
    chartData: {
      titleText: "ECharts 示例",
      xAxisData: ["数据1", "数据2", "数据3", "数据4", "数据5", "数据6"],
      seriesData: [5, 20, 36, 10, 10, 20]
    }
  }),
  actions: {
    // 设置图表数据
    setChartData(data) {
      this.chartData = data;
      if (this.chartInstance) {
        this.updateChart();
      }
    },

    // 初始化图表
    initChart(chartRef) {
      if (this.chartInstance) return; // 防止重复初始化
      if (chartRef) {
        this.chartInstance = echarts.init(chartRef);
        this.updateChart();
        this.isChartInitialized = true;
      }
    },

    // 更新图表配置项
    updateChart() {
      const option = {
        title: {
          text: this.chartData.titleText,
          left: "center", // 标题居中
          textStyle: {
            color: "#FFFFFF", // 设置标题颜色为白色
          },
        },
        tooltip: {},
        xAxis: {
          data: this.chartData.xAxisData,
          axisLabel: {
            color: "#FFFFFF", // 设置x轴文字颜色为白色
          },
        },
        yAxis: {
          axisLabel: {
            color: "#FFFFFF", // 设置y轴文字颜色为白色
          },
        },
        series: [
          {
            name: "销量",
            type: "line",
            data: this.chartData.seriesData,
          },
        ],
      };
      this.chartInstance.setOption(option);
    },

    // 销毁图表实例以避免内存泄漏
    disposeChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
        this.isChartInitialized = false;
      }
    },
  },
});